<template>
    <div class="dict-container">
        <div class="dict-tree" v-loading="treeLoading">
            <div class="flexd">
                <el-button size="small" icon="el-icon-plus" round @click="addType">
                    {{ translate('label.addCategory') }}
                </el-button>
            </div>
            <el-tree
                ref="tree"
                class="filter-tree"
                :data="treeData"
                :props="defaultProps"
                :check-strictly="true"
                default-expand-all
                node-key="code"
                highlight-current
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                @node-click="onClickTreeNode">
            </el-tree>
        </div>
        <div class="right-row">
            <el-form ref="dataDictDetail"
                     label-width="80px"
                     :rules="rules"
                     :model="currentTreeData"
                     label-position="right"
                     class="creAddForm tempCreAddForm data_dict">
                <el-form-item :label="translate('label.dictCode') +':'" prop="parentCode" disabled>
                    <el-input v-model="currentTreeData.parentCode" readonly disabled class="readonly"/>
                </el-form-item>
                <el-form-item :label="translate('label.dictCode') +':'" prop="code" disabled>
                    <el-input v-model="currentTreeData.code" readonly class="readonly"/>
                </el-form-item>
                <el-form-item :label="translate('label.dictVal') +':'" prop="value">
                    <el-input v-model="currentTreeData.value"/>
                </el-form-item>
                <el-form-item :label="translate('label.dictName') +':'" prop="name">
                    <el-input v-model="currentTreeData.name"/>
                </el-form-item>
                <el-form-item :label="translate('label.order') +':'" prop="orderNum">
                    <el-input v-model="currentTreeData.orderNum"/>
                </el-form-item>
                <el-form-item :label="translate('label.Languages') +':'" prop="language">
                    <el-select v-model="currentTreeData.language" :placeholder="translate('label.selectLanguage')"
                               class="select-item">
                        <el-option v-for="lan in languageList" :key="lan.value" :label="lan.label" :value="lan.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item :label="translate('label.updateDate') +':'" prop="updateDate">
                    <el-input v-model="currentTreeData.updateDate"/>
                </el-form-item>
                <el-form-item :label="translate('label.comment') +':'" prop="desc">
                    <el-input v-model="currentTreeData.desc" type="textarea" rows="1"/>
                </el-form-item>
                <el-form-item label="">
                    <el-button type="primary" size="small" icon="el-icon-edit" @click="changeParent">
                        {{ translate('button.modify') }}
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" @click="delParent">
                        {{ translate('button.delete') }}
                    </el-button>
                </el-form-item>
            </el-form>

            <div class="but-container part-btn">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addRow">
                    {{ translate('button.add') }}
                </el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="delChild">
                    {{ translate('button.batchDeletion') }}
                </el-button>
            </div>
            <div class="table-row">
                <el-table v-loading="tableLoading"
                          :data="tableData"
                          row-key="tid"
                          tooltip-effect="dark"
                          highlight-current-row
                          @selection-change="handleSelectChange">
                    <el-table-column type="selection" width="55" :reserve-selection="true"/>
                    <el-table-column prop="code" show-overflow-tooltip :label="translate('label.dictCode')"/>
                    <el-table-column prop="name" show-overflow-tooltip :label="translate('label.dictName')"/>
                    <el-table-column prop="value" show-overflow-tooltip :label="translate('label.dictVal')"/>
                    <el-table-column prop="language" :label="translate('label.Languages')" show-overflow-tooltip/>
                    <el-table-column prop="orderNum" :label="translate('label.sort')" show-overflow-tooltip/>
                    <el-table-column prop="desc" :label="translate('label.comment')" show-overflow-tooltip/>
                    <el-table-column :label="translate('label.operation')" align="left" width="200">
                        <template slot-scope="scope">
                            <el-link icon="el-icon-edit" type="primary" size="mini" @click="editRow(scope.row)">
                                {{ translate('button.edit') }}
                            </el-link>
                            <el-link icon="el-icon-delete" type="danger" size="mini" @click="delRow(scope.row)">
                                {{ translate('button.delete') }}
                            </el-link>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="searchParams.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="searchParams.totalRows"
                    style="text-align: right;"
                    @size-change="pageSizeChange"
                    @current-change="pageIndexChange"/>
            </div>

            <el-drawer :title="type=='add'? translate('button.add'):type=='edit'? translate('button.edit'):''"
                       :visible.sync="addEditFlag" direction="rtl"
                       :wrapperClosable="false" :before-close="cancelClose">
                <!--<addEdit :data="itemData" :type="type"  @cancel="cancelClose" @success="success" :isAddType="isAddType" v-if="addEditFlag" />-->
            </el-drawer>
        </div>
    </div>
</template>
<script lang="ts">
import _ from 'lodash';
import {Component} from "vue-property-decorator";
import BaseVue from '@/common/base-vue'
import DictService from '@/views/system/dict/dict.service';

@Component({components: {}})
export default class dict extends BaseVue {
    // 语言下拉选
    public languageList = [
        {label: 'zh_CN', value: 'zh_CN'},
        {label: 'en_US', value: 'en_US'},
    ];
    public defaultProps = {
        children: 'children',
        label: 'name',
    };
    public currentTreeData = {};
    public treeData = [];
    public tableData = [];
    public tableLoading = false;
    public treeLoading = false;
    public rules = {
        code: [{required: true, message: '请输入字典编码', trigger: 'blur'}],
        name: [{required: true, message: '请输入字典名称', trigger: 'blur'}],
        language: [{required: true, message: '请选择字典语言种类', trigger: 'blur'}]
    };
    public searchParams = {
        pageIndex: 1,
        pageSize: 10,
    };
    public checkList = [];
    public itemData = {};
    public addEditFlag = false;
    //新增数据字典分类
    public isAddType = false;
    public type = '';

    //生命周期created
    public created() {
    };

    //生命周期mounted
    public mounted() {
        this.getTreeData();
    };

    public filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    };

    //获取tree数据
    public getTreeData() {
        this.treeLoading = true;
        DictService.findAllSysDataDict({pageSize: 20, pageIndex: 1}).then(res => {
            if (res.status === 200) {
                this.treeData = res.data;
                this.treeLoading = false;
                //初始化进来请求第一个
                this.currentTreeData = !_.isEmpty(this.treeData) ? this.treeData[0] : {};
                this.onClickTreeNode(this.currentTreeData);
            }
        });
    };

    //节点被点击
    public onClickTreeNode(data) {
        this.currentTreeData = data;
        this.getTreeNodeData();
        this.getRightTbaleData();
        //多选操作的清空
        this.checkList = [];
    };

    // 查询当前标签的子节点
    public getTreeNodeData() {
        DictService.getDataDictTree({code: this.currentTreeData.code}).then(res => {
            const node = this.$refs['tree'].getNode(this.currentTreeData.code);
            this.$refs['tree'].setCurrentKey(this.currentTreeData.code);
            //内置方法 1、得到选中的节点2、将选中节点的子节点全部删除 3、将选中节点的子节点数据手动刷到该节点内
            const theChildren = node.childNodes;
            theChildren.splice(0, theChildren.length);
            node.doCreateChildren(res.data);

        }).catch(e => {
        });
    };

    // 查询子类列表
    public async getRightTbaleData() {
        this.tableLoading = true;
        let data = {
            pageIndex: this.searchParams.pageIndex,
            pageSize: this.searchParams.pageSize,
            code: this.currentTreeData.code,
        };

        const res = await DictService.getPagedChildrenList(data);
        this.tableLoading = false;
        if (res.status == 200) {
            this.tableData = res.data;
            this.searchParams.pageIndex = res.pageIndex;
            this.searchParams.pageSize = res.pageSize;
            this.searchParams.totalRows = res.totalRows;
        }
    };

    //多选操作
    public handleSelectChange(val) {
        this.checkList = val;
    };

    //右侧头部修改点击事件
    public changeParent() {
        this.$confirm(this.translate('label.modifyData'), this.translate('label.Tips'), {
            cancelButtonClass: "btn-custom-cancel",
            confirmButtonText: this.translate('button.sure'),
            cancelButtonText: this.translate('button.cancel'),
            type: 'warning',
        }).then(async () => {
            await DictService.updateSysDataDict(this.currentTreeData);
            this.$message.success(this.translate('label.modifyDataSuccess'));
            //停留在当前修改页面；
            this.onClickTreeNode(this.currentTreeData);
        }).catch(err => {
        });
    };

    //删除tree菜单分类（右侧头部删除按钮点击事件）
    public delParent() {
        this.$confirm(this.translate('label.delData'), this.translate('label.Tips'), {
            cancelButtonClass: "btn-custom-cancel",
            confirmButtonText: this.translate('button.sure'),
            cancelButtonText: this.translate('button.cancel'),
            type: 'warning',
        }).then(async () => {
            const res = await DictService.deleteSysDataDict([this.currentTreeData]);
            if (res.status == 200) {
                this.$message.success(this.translate('label.delDataSuccess'));
                this.getTreeData();
            }
        });
    };

    //批量删除
    public delChild() {
        if (this.checkList.length > 0) {
            this.$confirm(this.translate('label.delDataAll'), this.translate('label.Tips'), {
                cancelButtonClass: "btn-custom-cancel",
                confirmButtonText: this.translate('button.sure'),
                cancelButtonText: this.translate('button.cancel'),
                type: 'warning'
            }).then(async () => {
                const res = await DictService.deleteSysDataDict(this.checkList);
                if (res.status == 200) {
                    this.$message.success(this.translate('label.delDataSuccess'));
                    this.onClickTreeNode(this.currentTreeData)
                }
            });
        } else {
            return this.$message.warning(this.translate('label.noSelectData'));
        }
    };

    //table列表删除
    public delRow(row) {
        this.$confirm(this.translate('label.delData'), this.translate('label.Tips'), {
            cancelButtonClass: "btn-custom-cancel",
            confirmButtonText: this.translate('button.sure'),
            cancelButtonText: this.translate('button.cancel'),
            type: 'warning'
        }).then(async () => {
            const res = await DictService.deleteSysDataDict([row]);
            if (res.status == 200) {
                this.$message.success(this.translate('label.delDataSuccess'));
                this.onClickTreeNode(this.currentTreeData);
            }
        });
    };

    //新增tree菜单大类
    public addType() {
        this.type = 'add'
        if (this.currentTreeData.parentCode) {
            this.itemData.parentCode = this.currentTreeData.code,
                this.itemData.parentId = this.currentTreeData.tid
        } else {
            this.isAddType = true;
        }
        this.addEditFlag = true;
    };

    //新增table字典
    public addRow() {
        this.type = 'add'
        this.itemData.parentCode = this.currentTreeData.code,
            this.itemData.parentId = this.currentTreeData.tid,
            this.addEditFlag = true;
    };

    //编辑table字典
    public editRow(row) {
        this.type = 'edit';
        this.itemData = row;
        // this.itemData.parentCode = this.currentTreeData.code,
        // this.itemData.parentId = this.currentTreeData.tid,
        this.addEditFlag = true;
    };

    //弹窗修改确定
    public success() {
        if (this.isAddType) {
            this.getTreeData();
            this.isAddType = false;
        } else {
            this.onClickTreeNode(this.currentTreeData);
        }
        this.addEditFlag = false;
        this.itemData = {};
    };

    //弹窗关闭按钮
    public cancelClose() {
        this.itemData = {};
        this.isAddType = false;
        this.addEditFlag = false;
    };

    //翻页
    public pageSizeChange(val) {
        this.searchParams.pageSize = val;
        this.getRightTbaleData();
    };

    public pageIndexChange(val) {
        this.searchParams.pageIndex = val;
        this.getRightTbaleData();
    }

};
</script>
<style lang="scss" scoped>
//输入框
::v-deep .el-form-item__content {
    .el-input--small {
        .el-input__inner {
            width: 400px;
        }
    }
}

::v-deep .el-textarea__inner {
    width: 400px;
}

.dict-container {
    .right-row {
        background: #ffff;
        margin-left: 310px;
        height: calc(100vh - 150px);
        overflow: auto;
    }

    .tempCreAddForm {
        margin-bottom: 0 !important;
    }

    .el-form-item {
        margin-left: 20px;
        margin-bottom: 18px;
    }

    .readonly {
        input {
            cursor: no-drop;
            color: #999;
            background: #f5f5f5;
        }
    }

    .tabBox {
        background: #fff;
    }

    .dict-tree {
        position: absolute;
        width: 300px;
        background: #fff;
        z-index: 9;
        height: calc(100vh - 150px);
        overflow: auto;
        padding: 16px;
        font-size: 14px;

        .flexd {
            position: fixed;
            top: 100px;
            left: 225px;
            z-index: 10;
            padding: 0 100px;
            padding-top: 15px;
            padding-bottom: 10px;
            background: #fff;
        }

        .el-tree {
            padding-top: 40px;
        }
    }

    .el-drawer__body {
        .el-form-item__content .el-input__inner {
            width: 100%;
        }

        .el-textarea {
            width: 100%;
        }
    }

    .data_dict {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        background: #fff;
        padding: 16px;
        margin-bottom: 20px
    }


    .select-item {
        width: 100%;

        .el-input--suffix .el-input__inner {
            padding-right: 15px;
        }
    }

    :focus {
        outline: 0;
    }

    .el-textarea__inner {
        padding: 5px 13px;
    }
}

</style>
